package top.oylan.manager.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.oylan.manager.entity.User;
import top.oylan.manager.entity.api.BaseApi;
import top.oylan.manager.service.UserService;
import top.oylan.manager.tools.Directory;
import top.oylan.manager.tools.FileUploader;
import top.oylan.manager.tools.Result;
import top.oylan.manager.tools.SMSService;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-06-23
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Api(value = "user", description = "用户中心", produces = MediaType.APPLICATION_JSON_VALUE)
public class ApiUserController {

    @Resource
    UserService userService;

    @Resource
    FileUploader fileUploader;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public Result index(){

       return new Result();
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiOperation(value = "修改用户信息",response = BaseApi.class,httpMethod = "POST")
    public BaseApi updateUserInfo(@RequestBody User user){

        BaseApi api = new BaseApi();
        int res = userService.updateUser(user);
        api.setCode(0);
        api.setMsg("修改失败");
        if(res > 0){
            api.setCode(200);
            api.setMsg("编辑成功");
        }
        return api;
    }


    /**
     *
     * @param oldPassword
     * @param password
     * @return
     */
    @RequestMapping(value = "/password",method = RequestMethod.POST)
    @ApiOperation(value = "修改密码",response = BaseApi.class,httpMethod = "POST")
    public BaseApi updatePassword(@RequestParam("id")Integer id,
                                  @RequestParam("oldPassword")String oldPassword,
                                  @RequestParam("password")String password) {

        BaseApi api = new BaseApi();
        api.setCode(0);
        if(id == null || id == 0){
            api.setMsg("授权已过期，请重新登录");
            api.setCode(100);
        }else if(StringUtils.isEmpty(oldPassword)){
            api.setMsg("请输入旧密码");
        }else if (StringUtils.isEmpty(password)){
            api.setMsg("请输入新密码");
        }else{
            User user = userService.selectUserById(id);
            ByteSource salt = ByteSource.Util.bytes(user.getId().toString());
            SimpleHash simpleHash = new SimpleHash("md5", oldPassword, salt, 12);
            if(user.getPassword().equals(simpleHash.toString())){
                SimpleHash hash = new SimpleHash("md5", password, salt, 12);
                user.setPassword(hash.toString());
                userService.updateUser(user);
                api.setCode(200);
            }else{
                api.setMsg("原始密码错误");
            }
        }
        return api;
    }

    private static final String MSG_VERIFY_CODE = "message_verify_code";
    /**
     * 发生短信
     * @param phone
     * @return
     */
    @RequestMapping(value = "/send",method = RequestMethod.GET)
    public BaseApi sendMsg(@RequestParam("phone")String phone, HttpServletRequest request){

        BaseApi api = new BaseApi();
        api.setCode(0);
        User user= userService.findUserByPhone(phone);
        if(user==null){
            String code = SMSService.getRandomString(6);
            HttpSession session = request.getSession();
            session.setAttribute(MSG_VERIFY_CODE,code);

//            boolean res = SMSService.mobileQuery(phone, code);
            boolean res = true;
            if(res){
                api.setCode(200);
            }
        }else{
            api.setCode(1);
            api.setMsg("该手机号已被使用");
        }
        return api;
    }

    @RequestMapping(value = "/phone",method = RequestMethod.POST)
    @ApiOperation(value = "更新手机号",response = BaseApi.class,httpMethod = "POST")
    public BaseApi updatePhone(@RequestParam("id")Integer id,
                               @RequestParam("code")String code,
                               @RequestParam("phone")String phone,
                               HttpServletRequest request) {

        BaseApi api = new BaseApi();
        if(id == null || id == 0){
            api.setMsg("授权已过期，请重新登录");
            api.setCode(100);
        }else if(StringUtils.isEmpty(code)){
            api.setCode(0);
            api.setMsg("请输入验证码");
        }else if(StringUtils.isEmpty(phone)){
            api.setCode(0);
            api.setMsg("请输入手机号");
        }else if(!checkMsgVerifyCode(code,request.getSession())){
            api.setCode(0);
            api.setMsg("验证码错误");
        } else{
            User user = userService.selectUserById(id);
            user.setPhone(phone);
            updateUserInfo(user);
        }
        return api;
    }

    private boolean checkMsgVerifyCode(String code,HttpSession session) {
       String old = (String) session.getAttribute(MSG_VERIFY_CODE);
       return old!=null?old.equals(code):false;
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public BaseApi upload(Integer id ,MultipartFile file){
        BaseApi api = new BaseApi();
        api.setCode(0);
        api.setMsg("上传失败");
        Result res = fileUploader.upload(file, Directory.USER);
        if(res.getCode() == 1){
            User user = new User();
            user.setId(id);
            user.setAvatar((String) res.getData().get("path"));
            userService.updateUser(user);
            Map<String, Object> data = res.getData();
            api.setData(data);
            api.setMsg("上传成功");
            api.setCode(200);
        }
        return api;
    }


}
